import tkinter as tk
from tkinter import ttk, messagebox
import wmi
import ctypes
import winreg
import subprocess
import os
import sys
import threading
from PIL import Image, ImageDraw
import pystray
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL, CoInitialize, CoUninitialize

# ====== 获取当前亮度 ======
def get_brightness():
    try:
        wmi_interface = wmi.WMI(namespace='wmi')
        brightness = wmi_interface.WmiMonitorBrightness()[0].CurrentBrightness
        return brightness
    except:
        return 50

# ====== 设置亮度 ======
def set_brightness(level, var=None):
    try:
        level = max(0, min(100, int(float(level))))
        if var:
            var.set(f"{level}%")
        wmi_interface = wmi.WMI(namespace='wmi')
        methods = wmi_interface.WmiMonitorBrightnessMethods()[0]
        methods.WmiSetBrightness(level, 0)
    except Exception as e:
        print("亮度设置错误:", e)

# ====== 获取当前音量 ======
def get_volume():
    try:
        devices = AudioUtilities.GetSpeakers()
        interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
        volume = cast(interface, POINTER(IAudioEndpointVolume))
        return int(volume.GetMasterVolumeLevelScalar() * 100)
    except:
        return 30

# ====== 设置音量 ======
def set_volume(level, var=None):
    try:
        level = max(0, min(100, float(level)))
        if var:
            var.set(f"{int(level)}%")
        devices = AudioUtilities.GetSpeakers()
        interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
        volume = cast(interface, POINTER(IAudioEndpointVolume))
        volume.SetMasterVolumeLevelScalar(level / 100.0, None)
    except Exception as e:
        print("音量设置错误:", e)

# ====== 设置主题（暗/亮） ======
def set_theme(dark: bool):
    try:
        reg_path = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Themes\Personalize'
        key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, reg_path, 0, winreg.KEY_SET_VALUE)
        value = 0 if dark else 1
        winreg.SetValueEx(key, 'AppsUseLightTheme', 0, winreg.REG_DWORD, value)
        winreg.SetValueEx(key, 'SystemUsesLightTheme', 0, winreg.REG_DWORD, value)
        winreg.CloseKey(key)
        ctypes.windll.user32.SendMessageTimeoutW(0xFFFF, 0x1A, 0, 0, 0, 100)
    except Exception as e:
        messagebox.showerror("主题设置错误", str(e))

# ====== 打开蓝牙设置 ======
def open_bluetooth_settings():
    try:
        subprocess.run(["start", "ms-settings:bluetooth"], shell=True)
    except Exception as e:
        messagebox.showerror("蓝牙设置错误", str(e))

# ====== 添加开机自启 ======
def add_to_startup(name="ControlPanel", path=None):
    try:
        if path is None:
            path = sys.executable
        key = winreg.OpenKey(
            winreg.HKEY_CURRENT_USER,
            r"Software\Microsoft\Windows\CurrentVersion\Run",
            0, winreg.KEY_SET_VALUE
        )
        winreg.SetValueEx(key, name, 0, winreg.REG_SZ, f'"{path}"')
        winreg.CloseKey(key)
        messagebox.showinfo("成功", f"已添加开机启动项：\n{path}")
    except Exception as e:
        messagebox.showerror("开机启动错误", str(e))

# ====== 取消开机自启 ======
def remove_from_startup(name="ControlPanel"):
    try:
        key = winreg.OpenKey(
            winreg.HKEY_CURRENT_USER,
            r"Software\Microsoft\Windows\CurrentVersion\Run",
            0, winreg.KEY_ALL_ACCESS
        )
        winreg.DeleteValue(key, name)
        winreg.CloseKey(key)
        messagebox.showinfo("成功", f"已取消开机启动项：{name}")
    except FileNotFoundError:
        messagebox.showwarning("提示", f"未找到启动项：{name}")
    except Exception as e:
        messagebox.showerror("删除启动项错误", str(e))

# ====== 托盘图标 ======
def create_tray_icon(root):
    def on_quit(icon, item):
        icon.stop()
        root.destroy()

    def on_show(icon, item):
        root.deiconify()

    image = Image.new('RGB', (64, 64), color='blue')
    draw = ImageDraw.Draw(image)
    draw.rectangle((16, 16, 48, 48), fill='white')

    icon = pystray.Icon("ControlPanel", image, "控制面板", menu=pystray.Menu(
        pystray.MenuItem("显示窗口", on_show),
        pystray.MenuItem("退出", on_quit)
    ))

    threading.Thread(target=icon.run, daemon=True).start()

# ====== 主窗口 ======
def main():
    CoInitialize()
    try:
        root = tk.Tk()
        root.title("控制面板")
        root.geometry("400x450")
        root.eval('tk::PlaceWindow . center')

        create_tray_icon(root)

        # 屏幕亮度
        ttk.Label(root, text="屏幕亮度", font=("Arial", 12)).pack(pady=(10, 2))
        brightness_var = tk.StringVar()
        ttk.Label(root, textvariable=brightness_var).pack()
        current_brightness = get_brightness()
        brightness_var.set(f"{current_brightness}%")
        brightness_slider = ttk.Scale(
            root, from_=0, to=100, orient="horizontal",
            command=lambda v: set_brightness(v, brightness_var)
        )
        brightness_slider.set(current_brightness)
        brightness_slider.pack(fill="x", padx=30)

        # 音量控制
        ttk.Label(root, text="音量", font=("Arial", 12)).pack(pady=(20, 2))
        volume_var = tk.StringVar()
        ttk.Label(root, textvariable=volume_var).pack()
        current_volume = get_volume()
        volume_var.set(f"{current_volume}%")
        volume_slider = ttk.Scale(
            root, from_=0, to=100, orient="horizontal",
            command=lambda v: set_volume(v, volume_var)
        )
        volume_slider.set(current_volume)
        volume_slider.pack(fill="x", padx=30)

        # 主题设置
        ttk.Label(root, text="主题模式", font=("Arial", 12)).pack(pady=(20, 5))
        theme_frame = ttk.Frame(root)
        theme_frame.pack()
        ttk.Button(theme_frame, text="暗模式", command=lambda: set_theme(True)).grid(row=0, column=0, padx=10)
        ttk.Button(theme_frame, text="亮模式", command=lambda: set_theme(False)).grid(row=0, column=1, padx=10)

        # 蓝牙设置
        ttk.Label(root, text="蓝牙设置", font=("Arial", 12)).pack(pady=(20, 5))
        ttk.Button(root, text="打开蓝牙设置", command=open_bluetooth_settings).pack()

        # 开机启动设置
        ttk.Label(root, text="开机启动", font=("Arial", 12)).pack(pady=(20, 5))
        startup_frame = ttk.Frame(root)
        startup_frame.pack()
        ttk.Button(startup_frame, text="添加开机启动", command=add_to_startup).grid(row=0, column=0, padx=10)
        ttk.Button(startup_frame, text="取消开机启动", command=remove_from_startup).grid(row=0, column=1, padx=10)

        # 窗口关闭最小化到托盘
        def hide_window():
            root.withdraw()
        root.protocol("WM_DELETE_WINDOW", hide_window)

        root.mainloop()
    finally:
        CoUninitialize()

if __name__ == "__main__":
    main()
